﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using WebUI.Controls;
using MyGeneration.dOOdads;

namespace WebUI.EditPages
{
    public partial class ViewRepair : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            lstRepair.ClientOnEditProblemPrototype = "showEditProblem";
            lstRepair.ClientOnUpdateStatusPrototype = "showUpdateStatus";
            lstRepair.ClientOnChangeRepairBoxPrototype = "showChangeRepairBox";
            if (!IsPostBack)
            {
                ReloadAll();


                RepairStatus status = RepairStatus.GetUnFinishStatus();
                Utilities.LoadDropDownListNoSort(ddlStatus, status.DefaultView, RepairStatus.ColumnNames.StatusName, RepairStatus.ColumnNames.ID, "--All--");
            }

            txtJobID.Focus();
            btnBookOut.Visible = Branches.CurrentBranchID == SessionUser.BranchID;
        }

        protected void btnReturnAsUnrepair_OnClick(object sender, EventArgs e)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                String str = lstRepair.GetCheckedStrItemIDs();
                RepairJob job = RepairJob.GetJobs(str);
                RepairStatusHistories hist = new RepairStatusHistories();
                string strBoxs = "";

                for (int i = 0; i < job.RowCount; i++)
                {
                    job.StatusID = RepairStatus.Returned;
                    job.LastModifiedByUser = SessionUser.ID;
                    job.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    if(strBoxs.IndexOf(job.s_RepairBoxID + ",") < 0)
                        strBoxs += job.s_RepairBoxID + ",";
                    job.MoveNext();
                }
                
                job.Save();
                job.Rewind();
                for (int i = 0; i < job.RowCount; i++)
                {
                    hist.AddNew();
                    hist.BranchID = Branches.CurrentBranchID;
                    hist.RepairJobID = job.ID;
                    hist.RepairStatusID = job.StatusID;
                    hist.UpdatedByUser = SessionUser.ID;
                    hist.UpdatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    hist.Save();

                    job.MoveNext();
                }
                hist.Save();

                string[] boxIDs = strBoxs.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < boxIDs.Length; i++)
                {
                    View_RepairJobs.UpdateRepairBoxStatus(int.Parse(boxIDs[i]));
                }

                tx.CommitTransaction();

                ReloadAll();
                updateCust.Update();
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("ViewRepair.aspx.cs", "btnReturnAsUnrepair_OnClick", ex.StackTrace);
            }
        }

        private void ReloadAll()
        {
            View_RepairJobs jbs = View_RepairJobs.GetCurrentJobs();
            jbs.Sort = View_RepairJobs.ColumnNames.CreatedDate + " desc";
            lstRepair.Jobs = jbs;
            lstRepair.JobProblems = null;
            lstRepair.JobStatusHist = null;
            lstRepair.SortExpression = View_RepairJobs.ColumnNames.CreatedDate;
            lstRepair.SortDirection = BaseListControl.SORT_DESC;
            lstRepair.CurrentPageIndex = 0;
            lstRepair.Refresh();

            View_RepairCustomers custs = View_RepairCustomers.GetCurrentRepairCustomer();
            lstCust.SourceObject = custs;
            lstCust.OnClientClick = "loadRepairByCustID();";
            lstCust.Refresh();
            lstCust.Columns[0].Visible = false;

            if (lstCust.SelectedValue != "")
            {
                string oldFilter = custs.Filter;
                custs.Filter = View_RepairCustomers.ColumnNames.CustomerID + "=" + lstCust.SelectedValue;
                if (custs.RowCount > 0)
                    LoadByCustID();
                else
                    lstCust.SelectedValue = "";
                custs.Filter = oldFilter;
            }
        }

        protected void btnLoadAll_OnClick(object sender, EventArgs e)
        {
            ReloadAll();
            updateCust.Update();
        }

        public string GetSalePage(string key)
        {
            return this.ResolveUrl("~/EditPages/RepairSales.aspx?key=" + key);
        }

        protected void btnBookOut_OnClick(object sender, EventArgs e)
        {
            string key = Guid.NewGuid().ToString();
            try
            {
                int[] ids = lstRepair.GetCheckedItemIDs();
                Session[key] = ids;

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showSale('{0}');", GetSalePage(key)), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ViewRepair.aspx.cs", "btnBookOut_OnClick", ex.StackTrace);
                Session.Remove(key);
            }
        }

        protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlStatus.SelectedIndex > 0)
                lstRepair.Filter = View_RepairJobs.ColumnNames.StatusID + " = " + ddlStatus.SelectedValue;
            else if (ddlStatus.SelectedValue == "-1")
                lstRepair.Filter = "not " + View_RepairJobs.ColumnNames.StatusID + " > 0";
            else
                lstRepair.Filter = "";
            lstRepair.CurrentPageIndex = 0;
            lstRepair.Refresh();
            //lstRepair.Filter = "";
        }

        protected void btnLoadByJobID_OnClick(object sender, EventArgs e)
        {
            lstRepair.Filter = View_RepairJobs.ColumnNames.RepairNo + " LIKE '%" + txtJobID.Text + "%'";
            lstRepair.CurrentPageIndex = 0;
            lstRepair.Refresh();
            //lstRepair.Filter = "";

        }

        protected void btnLoadByCustID_OnClick(object sender, EventArgs e)
        {
            if(lstCust.SelectedValue != "")
                LoadByCustID();
        }

        private void LoadByCustID()
        {
           // String filter = lstRepair.Filter;

            String condition = "CustomerID =" + lstCust.SelectedValue;
            if (lstCust.SelectedValue == "0")
                condition = "CustomerID IS NULL";

            //if (lstRepair.Filter != "")
            //    lstRepair.Filter += " and " + condition;
            //else
                lstRepair.Filter = condition;
            lstRepair.CurrentPageIndex = 0;
            lstRepair.Refresh();
            //lstRepair.Filter = filter;
        }

        public string GetEditRepairProblemLink(){
            return this.ResolveUrl("~/EditPages/EditRepairProblem.aspx");
        }

        public string GetUpdateStatusLink()
        {
            return this.ResolveUrl("~/EditPages/UpdateStatus.aspx");
        }

        public string GetConfirmReturnLink()
        {
            return this.ResolveUrl("~/EditPages/ConfirmReturn.aspx");
        }

        public string GetRepairBoxLink()
        {
            return this.ResolveUrl("~/EditPages/ChangeRepairBox.aspx");
        }
    }
}